package com.pianke.yc.test.View;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.pianke.yc.test.R;

/**
 * Created by YC on 2016/3/31.
 */
public class LoadMoreListView extends ListView implements AbsListView.OnScrollListener {

    private View footer;
    private int startItem;
    private int totaItem;
    private int lastItm;
    private static boolean isFirst=true;

    private boolean isLoading;

    private LayoutInflater infalter;
    private OnLoadMore onLoadMore;

    public LoadMoreListView(Context context) {
        super(context);
        init(context);
    }

    public LoadMoreListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public LoadMoreListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        infalter = LayoutInflater.from(context);
        footer = infalter.inflate(R.layout.load_more_footer, null, false);
        footer.setVisibility(View.GONE);
        this.addFooterView(footer);
        this.setOnScrollListener(this);

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        if (scrollState == SCROLL_STATE_IDLE) {
            if (this.totaItem == lastItm) {
                isLoading = true;
                footer.setVisibility(View.VISIBLE);
                onLoadMore.loadMore();
            }
        }else{

        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.startItem = firstVisibleItem;
        this.lastItm = firstVisibleItem + visibleItemCount;
        this.totaItem = totalItemCount;
        if(isFirst && visibleItemCount!=0) {
            isFirst=false;

        }
    }

    public void setLoadMoreListen(OnLoadMore onLoadmoew) {
        this.onLoadMore = onLoadmoew;
    }

    public void onLoadComplete() {
        footer.setVisibility(View.GONE);
        isLoading = false;
    }

    public interface OnLoadMore {
        public void loadMore();
    }
}
